package com.itboye.hutouben.util;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.Toast;

import com.itboye.hutouben.R;
import com.itboye.hutouben.util.BaseDialogFragment;
import com.itboye.hutouben.util.SelectImageView;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.animation.ObjectAnimator;

/**
 * ����ɡ�����
 */
public class PhotoSelectFragment extends BaseDialogFragment implements
        OnClickListener {

    private Button ok;
    Button cancel;
    private GridView gridview;
    ArrayList<Boolean> isSelect;
    List<String> selectPath = new ArrayList<String>();
    private PhotoSelectListener listener;
    int maxCount;
    int count;

    public PhotoSelectFragment() {

    }

    @SuppressLint("ValidFragment")
    public PhotoSelectFragment(PhotoSelectListener listener, int maxCount) {
        // TODO Auto-generated constructor stub
        this.listener = listener;
        this.maxCount = maxCount;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        return LayoutInflater.from(getActivity()).inflate(
                R.layout.fragment_photo_select, null);

    }

    private int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height",
                "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        int h = getActivity().getWindowManager().getDefaultDisplay()
                .getHeight()
                - getStatusBarHeight();
        ObjectAnimator.ofFloat(getView(), "translationY", h, 0)
                .setDuration(300).start();
        final ArrayList<String> listImage = new ArrayList<String>();
        isSelect = new ArrayList<Boolean>();
        // ɨ���ⲿ�豸�е���Ƭ
        String str[] = { MediaStore.Images.Media._ID,
                MediaStore.Images.Media.DISPLAY_NAME,
                MediaStore.Images.Media.DATA };
        Cursor cursor = getActivity().getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, str, null, null,
                null);
        while (cursor.moveToNext()) {
            int i = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
            listImage.add(cursor.getString(i));
            isSelect.add(false);
        }
        cursor.close();

        gridview.setAdapter(new MyAdapter(listImage));

        gridview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                // view.setSelected(!view.isSelected());
                //
                boolean b = !isSelect.get(position);

                if (b) {
                    if (count == maxCount) {
                        toast("最多可选" + maxCount + "张");
                        return;
                    }
                }

                isSelect.set(position, b);

                ((SelectImageView) view).setSelectViewSelected(b);

                if (b) {
                    count++;
                    selectPath.add(listImage.get(position));
                } else {
                    count--;
                    selectPath.remove(listImage.get(position));
                }

                ok.setText("选中" + count + "张");
            }
        });

    }

    class MyAdapter extends BaseAdapter {

        ArrayList<String> listImage;
        float width;

        public MyAdapter(ArrayList<String> listImage) {
            width = (getActivity().getWindowManager().getDefaultDisplay()
                    .getWidth() - getResources().getDimension(
                    R.dimen.DIMEN_5DP) * 4) / 3;
            this.listImage = listImage;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return listImage.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = new SelectImageView(getActivity());

                AbsListView.LayoutParams params = new AbsListView.LayoutParams(
                        (int) width, (int) width);

                convertView.setLayoutParams(params);

            }
            SelectImageView selectImageView = (SelectImageView) convertView;

            // �����ļ�����
            /****
             * @author 10-8
             */

            XImageLoader.load("file://" + listImage.get(position),
                    selectImageView.iv);
            ((SelectImageView) selectImageView).setSelectViewSelected(isSelect
                    .get(position));
            return selectImageView;
        }

    }

    @Override
    public void onClick(View v) {
        int h = getActivity().getWindowManager().getDefaultDisplay()
                .getHeight()
                - getStatusBarHeight();
        ObjectAnimator animator = ObjectAnimator.ofFloat(getView(),
                "translationY", 0, h).setDuration(300);

        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                // TODO Auto-generated method stub
                super.onAnimationEnd(animation);
                dismiss();
            }
        });
        animator.start();

        switch (v.getId()) {
            case R.id.ok:
                if (listener != null) {

                    listener.onPhotoSelectFinish(selectPath);
                }
                break;

            case R.id.cancel:
                if (listener != null) {
                    listener.onPhotoSelectFinish(new ArrayList<String>());
                }
                break;
            default:
                break;
        }

    }

    public interface PhotoSelectListener {
        /**
         * ����ɡ�����
         *
         * @param paths
         */
        void onPhotoSelectFinish(List<String> paths);
    }
}
